/* This program will read in a C program, and print out the variables
** that match by the first 6 digits.  It is an exercise found on page
** 143 of the c new testament
*/

#define _GNU_SOURCE 1

#include <stdio.h>
#include <regex.h>
#include <string.h>
#include <stdbool.h>
#include <argp.h>
#include "list.h"

bool i = false;
bool o = false;
char filename_string [128]; 
char outputFileName [128];

const char * argp_program_version = "0.1";
/* mail bug reports to */
const char * argp_program_bug_address = "jbranso@fastmail.com";

static const struct argp_option options [] =
  {
   {"input", 'i',  "FILE", 0, "Reads the file and outputs the variables, whose first 6 digits match." },
   {"output", 'o', "FILE", OPTION_ARG_OPTIONAL, "output to save the file"},
   { 0 }
  };

//parse options
error_t argp_parser (int opt, char *arg, struct argp_state *state) {
  extern bool i, o;
  extern char filename_string [128];
  switch (opt)
    {
      // if this parser function is called on an option that it doesn't recognize, then don't do anything.
    default:
      return ARGP_ERR_UNKNOWN;
    case 'i':
      {
        i = true;
        memcpy (filename_string, arg, strlen (arg));
        break;
      }
    case 'o':
      {
        o = true;
        printf ("file is %s\n", arg);
        memcpy (outputFileName, arg, strlen (arg));
        break;
      }
    }
  return 0;
}

struct argp argp =
  { options, argp_parser, 0, "Deletes trailing whitespace." };

int main (int argc, char **argv) {

  extern char filename_string [128];
  extern bool i;

  argp_parse (&argp, argc, argv, 0, 0, 0);

  FILE * input_file_stream;

  input_file_stream = fopen(filename_string, "r+");
  if (input_file_stream == NULL) // if there is no stream opened, print an error message
    {
      perror ("fopen");  //print an error to the stderr stream
      exit (EXIT_FAILURE);
    }
  store_c_file_common_variables (input_file_stream);
  print_c_file_common_variables (input_file_stream);
  fclose (input_file_stream);
  return 0;
}


